<template>
  <div id="container">
    <el-row :gutter="10">
      <el-col :span="5">
        <el-scrollbar :style="scrollHeight">
          <el-card shadow="never" :body-style="contentViewHeight">
            <div class="title">知识数据目录</div>
            <el-tree
              :data="deptOptions"
              :props="defaultProps"
              :expand-on-click-node="false"
              ref="tree"
              node-key="id"
              default-expand-all
              highlight-current
              @node-click="handleNodeClick"
            />
          </el-card>
        </el-scrollbar>
      </el-col>
      <!--用户数据-->
      <el-col :span="19">
        <el-scrollbar :style="scrollHeight">
          <el-card shadow="never" :body-style="contentViewHeight">
            <el-form
              :model="queryParams"
              ref="queryForm"
              size="small"
              :inline="true"
              label-width="68px"
            >
              <el-form-item label="知识名称" prop="fileName">
                <el-input
                  v-model="queryParams.fileName"
                  placeholder="请输入知识名称"
                  clearable
                  style="width: 240px"
                />
              </el-form-item>
              <el-form-item label="发布状态" prop="fileName">
                <el-select v-model="queryParams.status" placeholder="请选择">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  size="small"
                  @click="handleQuery"
                  >搜索</el-button
                >
                <el-button
                  icon="el-icon-refresh"
                  size="small"
                  @click="resetQuery"
                  >重置</el-button
                >
              </el-form-item>
            </el-form>
            <el-table
              v-loading="loading"
              :data="userList"
              :max-height="tableClientHeight"
            >
              <el-table-column
                label="知识名称"
                prop="knowledgeName"
                fixed="left"
                width="240px"
                show-overflow-tooltip
              />
              <el-table-column
                fixed="left"
                width="240px"
                label="源文件名称"
                align="center"
                prop="fileName"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                label="文件版次"
                align="center"
                prop="fileVersion"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                label="文件编号"
                align="center"
                prop="fileCode"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                label="上传人员"
                align="center"
                prop="uploadUser"
              />
              <el-table-column
                label="作者姓名"
                align="center"
                prop="author"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                label="数据来源"
                align="center"
                prop="fileSource"
              />
              <el-table-column
                label="上传日期"
                align="center"
                prop="uploadTime"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                label="文件格式"
                align="center"
                prop="fileFormat"
              />
              <el-table-column
                label="解析状态"
                align="center"
                prop="analyseStatusName"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                label="发布状态"
                align="center"
                prop="dataStatusName"
              />

              <el-table-column
                label="操作"
                align="center"
                fixed="right"
                class-name="small-padding fixed-width"
                width="200px"
              >
                <template slot-scope="scope">
                  <!-- 解析失败仅支持查看 -->
                  <el-button
                    size="mini"
                    type="text"
                    v-if="
                      scope.row.dataStatus == 3 ||
                      scope.row.permissionVo.unpublished
                    "
                    @click="edit(scope.row, true)"
                    >查看</el-button
                  >
                  <el-button
                    size="mini"
                    type="text"
                    v-if="
                      scope.row.permissionVo.release &&
                      scope.row.dataStatus != 3
                    "
                    @click="edit(scope.row, false)"
                    >编辑</el-button
                  >
                  <el-button
                    size="mini"
                    type="text"
                    v-if="
                      scope.row.permissionVo.release &&
                      scope.row.dataStatus != 3
                    "
                    @click="release(scope.row)"
                    >发布</el-button
                  >
                  <el-button
                    size="mini"
                    type="text"
                    v-if="scope.row.permissionVo.unpublished"
                    @click="quitRelease(scope.row)"
                    >取消发布</el-button
                  >
                </template>
              </el-table-column>
            </el-table>

            <el-pagination
              @size-change="sizeChangeHandle"
              @current-change="currentChangeHandle"
              :current-page="pageNo"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="pageSize"
              :total="total"
              style="text-align: right; margin-top: 10px"
              layout="total, sizes, prev, pager, next, jumper"
            >
            </el-pagination>
          </el-card>
        </el-scrollbar>
      </el-col>
    </el-row>

    <!-- 预览 -->
    <el-dialog
      custom-class="preview"
      :visible.sync="previewVisible"
      fullscreen
      center
      :close-on-click-modal="false"
      :before-close="closePreview"
    >
      <el-form ref="form" class="form_title" :model="formTitle">
        <el-form-item label="原文件名称">
          <el-input v-model="formTitle.fileName" disabled></el-input>
        </el-form-item>
        <el-form-item label="知识名称" prop>
          <el-input
            :disabled="isView"
            v-model="formTitle.knowledgeName"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>

      <el-row
        :gutter="20"
        style="margin-top: 20px; width: 100%; height: 100% !important"
        v-loading="isLoading"
      >
        <el-col :span="isView ? 24 : 12" style="height: 100%;">
          <iframe
            v-loading="previewLoading"
            id="iframe"
            ref="iframe"
            src=""
            frameborder="0"
            width="100%"
            height="100%"
          ></iframe>
        </el-col>
        <el-col v-if="!isView" :span="12">
          <div
            class="editorClass"
            :style="isView ? 'pointer-events: none;' : 'pointer-events: auto;'"
          >
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editor"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: calc(100% - 81px); overflow-y: hidden"
              v-model="html"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="onCreated"
            />
          </div>
        </el-col>
      </el-row>

      <span slot="footer" v-if="!isView" class="dialog-footer">
        <el-button type="primary" @click="submitFn">保存</el-button>
      </span>
    </el-dialog>

    <!-- 预览 -->
    <el-dialog
      custom-class="preview"
      :visible.sync="previewVideoVisible"
      fullscreen
      center
      :close-on-click-modal="false"
    >
      <div class="video_model">
        <div id="video"></div>
      </div>

      <div class="analysis">
        <el-card
          class="box-card"
          v-for="(item, index) in analysisData.content"
          :key="index"
        >
          <div slot="header" class="clearfix">
            <span v-if="item.seg_time"
              >时间段：{{ item.seg_time[0] }},{{ item.seg_time[1] }} 秒</span
            >
          </div>
          <div class="text item">
            <el-input
              type="textarea"
              placeholder="请输入内容"
              v-model="item.text"
              :autosize="{ minRows: 2 }"
            ></el-input>
          </div>
        </el-card>
      </div>

      <span slot="footer" v-if="!isView" class="dialog-footer">
        <el-button type="primary" @click="submitVideoFn">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { Boot } from "@wangeditor/editor";
import "@wangeditor/editor/dist/css/style.css";
import module from "./modules"
export default {
  components: {
    Editor,
    Toolbar,
  },
  name: "User",
  data() {
    return {
      previewVisible: false,
      previewVideoVisible: false,
      loading: true,
      previewLoading: true,
      dataInfo: "",
      total: 0,
      pageNo: 1,
      pageSize: 10,
      userList: null,
      title: "",
      deptOptions: [],
      form: {},
      formTitle: {
        eventName: "",
        knowledgeName: "",
      },
      options: [
        {
          value: 0,
          label: "待发布",
        },
        {
          value: 1,
          label: "已发布",
        },
        {
          value: 2,
          label: "发布中",
        },
        {
          value: 3,
          label: "发布失败",
        },
      ],
      defaultProps: {
        children: "children",
        label: "label",
      },
      queryParams: {
        fileName: "",
        fileType: null,
        profession: null,
        status: "",
      },
      editor: null,
      html: "<p></p>",
      toolbarConfig: {},
      editorConfig: {
        placeholder: "请输入内容...",
        MENU_CONF: {
          uploadImage: {},
        },
      },
      mode: "default", // or 'simple'
      analysisData: {},
      player: Object,
      isView: false,
      isLoading: true
    };
  },
  watch: {
    previewVideoVisible(newVal, oldVal) {
      if (newVal === false) {
        this.player.destroy();
      }
    },
  },
  computed: {
    contentViewHeight() {
      const height = document.documentElement["clientHeight"] - 120;
      return { minHeight: height + "px" };
    },
    scrollHeight() {
      const height = document.documentElement["clientHeight"] - 110;
      return { height: height + "px" };
    },
    tableClientHeight() {
      // let tableClientHeight =
      //   document.documentElement.clientHeight || document.body.clientHeight;
      // tableClientHeight = tableClientHeight - 259;
      // return tableClientHeight;
    },
  },
  created() {
    let that = this;
    this.editorConfig.MENU_CONF["uploadImage"] = {
      server: "/api/upload",
      // form-data fieldName ，默认值 'wangeditor-uploaded-image'
      fieldName: "your-custom-name",

      // 单个文件的最大体积限制，默认为 2M
      maxFileSize: 1 * 1024 * 1024, // 1M

      // 最多可上传几个文件，默认为 100
      maxNumberOfFiles: 10,

      // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
      allowedFileTypes: ["image/*"],

      // 自定义上传参数，例如传递验证的 token 等。参数会被添加到 formData 中，一起上传到服务端。
      meta: {
        token: "xxx",
        otherKey: "yyy",
      },

      // 将 meta 拼接到 url 参数中，默认 false
      metaWithUrl: false,

      // 自定义增加 http  header
      headers: {
        Accept: "text/x-json",
        otherKey: "xxx",
      },

      // 跨域是否传递 cookie ，默认为 false
      withCredentials: true,

      // 超时时间，默认为 10 秒
      timeout: 5 * 1000, // 5 秒
      customUpload: async (file, insertFn) => {
        console.log(file, "file");
        if (file) {
          const reader = new FileReader();
          // 当读取完成时触发
          reader.onload = function (e) {
            const base64String = e.target.result; // Base64 编码字符串
            console.log("打印文件信息", base64String);
            const imgTag = `<img src="${base64String}" style="max-width: 100%;" />`;
            // 将 img 标签插入到编辑器中
            console.log("实例===", that.editor);
            that.editor.dangerouslyInsertHtml(imgTag);
          };

          // 将文件读取为 Data URL (Base64)
          reader.readAsDataURL(file);
        }
      },
      // onBeforeUpload(file) {
      //   // JS 语法
      //   // file 选中的文件，格式如 { key: file }
      //   console.log("看看文件信息", file);
      //   that.fileToBase64(file);
      // },
    };
  },
  mounted() {
    this.getList();
    this.getDeptTree();
  },
  methods: {
    onCreated(editor) {
      Boot.registerModule(module)
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
    },
    fileToBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => {
          // 返回 Base64 字符串
          resolve(reader.result);
        };
        reader.onerror = reject;
        reader.readAsDataURL(file);
      });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageNo = 1;
      this.getList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageNo = val;
      this.getList();
    },
    getList() {
      this.loading = true;
      this.$http({
        url: "/knowledgeData/list",
        method: "GET",
        params: {
          ...this.queryParams,
          pageSize: this.pageSize,
          pageNumber: this.pageNo,
        },
      }).then(({ data }) => {
        this.userList = data.data.data;
        this.total = data.data.totalSize;
        this.loading = false;
      });
    },
    getDeptTree() {
      this.$http({
        url: "/knowledgeData/treeList",
        method: "GET",
        params: {},
      }).then(({ data }) => {
        this.deptOptions = data.data;
      });
    },
    // 节点单击事件
    handleNodeClick(data, node, item) {
      console.log(data, "data", node, item);
      if (node.level === 2) {
        this.queryParams.profession = node.parent.data.value;
        this.queryParams.fileType = data.value;
        this.getList();
      } else if (node.level === 1) {
        this.queryParams.profession = data.value;
        this.queryParams.fileType = null;
        this.getList();
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.fileName = "";
      this.queryParams.fileType = "";
      this.queryParams.profession = "";
      this.queryParams.status = "";
      this.pageNo = 1;
      this.$refs.tree.setCurrentKey(null);
      this.getList();
    },
    updateName() {
      this.$http({
        url: "/knowledgeData/updateName",
        method: "post",
        data: {
          id: this.dataInfo.id,
          knowledgeName: value,
        },
      }).then(({ data }) => {
        return data;
      });
    },
    closePreview() {
      if (this.formTitle.knowledgeName == "") {
        this.$message.warning("知识名称不能为空");
        return;
      }
      this.previewVisible = false;
    },
    // 保存
    submitFn() {
      if (this.formTitle.knowledgeName == "") {
        this.$message.warning("知识名称不能为空");
        return;
      }

      this.$http({
        url: "/knowledgeData/saveStatus",
        method: "get",
        params: {
          id: this.dataInfo.id,
        },
      }).then(({ data }) => {
        console.log(data);
        if (data.data == true) {
          // this.$confirm("是否保存本次对知识数据的更改？")
          //   .then((_) => {
            const editor = this.editor;
            if (editor == null) return;
            const content = editor.getHtml();
            console.log("fffff", content);
            const blob = new Blob([content], { type: "text/html" });
            const file = new File([blob], "example.html", {
              type: "text/html",
            });
            const formData = new FormData();
            formData.append("file", file);
            formData.append("id", this.dataInfo.id);

            for (const [key, value] of formData.entries()) {
              console.log(key, value);
            }
            console.log("formData===", formData);

            this.$http({
              url: "/knowledgeData/save",
              method: "post",
              data: formData,
            }).then(({ data }) => {
              console.log(data.data, "查看保存信息");
              if (data.code == 200) {
                // this.$message.success("保存成功");
                if (this.isView) {
                  this.previewVisible = false
                }
                // this.html = '';
                // this.$refs('iframe').src = '';
                // this.previewVisible = false;
              }
            });
            this.$http({
              url: "/knowledgeData/updateName",
              method: "post",
              data: {
                id: this.dataInfo.id,
                knowledgeName: this.formTitle.knowledgeName,
              },
            }).then(({ data }) => {
              //
            });
            // })
            // .catch((_) => {});
            this.$message.success("保存成功");
        } else {
          this.$message.warning("当前状态无法保存");
        }
      });
    },
    submitVideoFn() {
      console.log("formData===", this.analysisData);

      this.$http({
        url: "/knowledgeData/video/save",
        method: "post",
        data: {
          id: this.dataInfo.id,
          videoJson: JSON.stringify(this.analysisData),
        },
      }).then(({ data }) => {
        console.log(data.data, "查看保存信息");
        if (data.code == 200) {
          this.$message.success("保存成功");
          this.previewVideoVisible = false;
        }
      });
    },
    // convertHtmlToFile(data) {
    //   const htmlContent = data;
    //   const blob = new Blob([htmlContent], { type: 'text/html' });
    //   const file = new File([blob], 'file.html', { type: 'text/html' });
    //     // 现在 file 就是一个 File 类型的对象,可以进行后续的操作,比如上传到服务器等
    //     console.log(file);
    //   return file

    // },

    edit(row, isView) {
      this.isLoading = true
      this.isView = isView;
      console.log(row);
      this.dataInfo = row;
      if ([35, 38].includes(row.fileType)) {
        // 培训视频类型，0-课件，1-视频
        this.$http({
          url: "/knowledgeData/video/verification",
          method: "get",
          params: {
            id: row.id,
          },
        }).then(({ data }) => {
          this.analysisData = JSON.parse(data.data.videoJson);

          console.log("fff", this.analysisData);
        });
        this.$http({
          url: "/knowledgeData/preview",
          method: "get",
          params: {
            id: row.id,
          },
        }).then(({ data }) => {
          console.log("获取文件之后地址", data.data.downloadUrl);
          this.previewVideoVisible = true;
          setTimeout(() => {
            this.player = new this.$Player({
              id: "video", // 元素id
              lang: "zh", // 设置中文
              volume: 0, // 默认静音
              autoplay: false, // 自动播放
              screenShot: false, // 开启截图功能
              // 视频地址
              url: this.$config.VUE_APP_BASE_API_QA + data.data.downloadUrl,
              // 封面图
              // poster:'',
              fluid: true, // 填满屏幕 （流式布局）
              playbackRate: [0.5, 0.75, 1, 1.5, 2], // 传入倍速可选数组
            });
          }, 300);
        });
      } else {
        this.$http({
          url: "/knowledgeData/verification",
          method: "get",
          params: {
            id: row.id,
          },
        }).then(({ data }) => {
          console.log("原始文件地址", data);
          this.parsingFiles(
            [["token", +localStorage.getItem("token")]],
            this.$config.VUE_APP_BASE_API_QA + data.data.downloadUrl
          );
        });
        this.$http({
          url: "/knowledgeData/preview",
          method: "get",
          params: {
            id: row.id,
          },
        }).then(({ data }) => {
          this.previewVisible = true;
          this.formTitle = row;

          setTimeout(() => {
            var iframe = document.querySelector("#iframe");
            this.populateIframe(
              iframe,
              [["token", +localStorage.getItem("token")]],
              this.$config.VUE_APP_BASE_API_QA + data.data.downloadUrl
            );
          }, 0);
        });
      }
    },
    populateIframe(iframe, headers, url) {
      var xhr = new XMLHttpRequest();
      xhr.open("GET", url);
      xhr.responseType = "blob";
      headers.forEach((header) => {
        xhr.setRequestHeader(header[0], header[1]);
      });
      // xhr.setRequestHeader("X-Amz-Server-Side-Encryption-Customer-Key-MD5", "m7AXuOLSaEQc1369IHCZGw==")
      // xhr.setRequestHeader("X-Amz-Server-Side-Encryption-Customer-Algorithm", "AES256")
      // xhr.setRequestHeader("X-Amz-Server-Side-Encryption-Customer-Key", "5svVq6aMjTLMBTD0yaIT9u735QnpHteabx6nFZUXvac=")
      xhr.onreadystatechange = () => {
        if (xhr.readyState === xhr.DONE) {
          if (xhr.status === 200) {
            console.log(URL.createObjectURL(xhr.response), "ffff");
            this.previewUrl = URL.createObjectURL(xhr.response);
            console.log("预览地址", URL.createObjectURL(xhr.response));
            iframe.src =
              "./static/pdfjs/web/viewer.html?file=" +
              URL.createObjectURL(xhr.response);
            this.previewLoading = false;
          }
        }
      };
      xhr.send();
    },
    parsingFiles(headers, url) {
      var xhr = new XMLHttpRequest();
      xhr.open("GET", url);
      xhr.responseType = "blob";
      headers.forEach((header) => {
        xhr.setRequestHeader(header[0], header[1]);
      });

      xhr.onreadystatechange = async () => {
        if (xhr.readyState === xhr.DONE) {
          if (xhr.status === 200) {
            const blobUrl = URL.createObjectURL(xhr.response);
            console.log("预览地址", URL.createObjectURL(xhr.response));
            // 获取Blob URL的内容
            const response = await fetch(blobUrl);
            const text = await response.text();
            // 转换为HTML字符串
            // this.html = text;
            if (!this.isView) {
              // this.$nextTick(() => {
              setTimeout(() => {
                console.log('text', text)
                this.isLoading = false
                this.editor.setHtml(text);
              }, 2000);
            }
            // 清理URL对象URL.revokeObjectURL(blobUrl);
            URL.revokeObjectURL(blobUrl);
          }
        }
      };
      xhr.send();
    },
    release(row) {
      this.$confirm(
        `确定发布${row ? "[" + row.fileName + "]" : "选中项"}吗?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        this.$http({
          url: "/knowledgeData/release",
          method: "post",
          data: { ...row },
        }).then(({ data }) => {
          if (data.code == 200) {
            this.$message.success("发布成功");
          } else {
            this.$message.warning(data.msg);
          }
          this.loading = true
          setTimeout(() => {
            this.getList();
          }, 1000)
        });
      });
    },
    quitRelease(row) {
      this.$confirm(
        `确定取消发布${row ? "[" + row.fileName + "]" : "选中项"}吗?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        this.$http({
          url: "/knowledgeData/unreleased",
          method: "post",
          data: { ...row },
        }).then(({ data }) => {
          if (data.code == 200) {
            this.$message.success("取消发布成功");
          } else {
            this.$message.warning(data.msg);
          }
          this.getList();
        });
      });
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {},
  },
};
</script>

<style lang="scss" scoped>
#container {
  padding: 10px 20px 0;
  .title {
    margin-bottom: 10px;
  }
  .content_left_search {
    display: flex;
    align-items: center;
  }
}
.preview ::v-deep.el-dialog {
  margin-top: 0px !important;
}

.form_title {
  position: absolute;
  top: 20px;
  display: flex;
  width: 72%;
  justify-content: space-between;
  .el-form-item {
    display: flex !important;
  }
}

::v-deep .preview {
  .el-dialog__body {
    width: 100%;
    height: calc(100% - 120px);
    display: flex !important;
    justify-content: space-around;
  }
  .el-dialog__footer {
    margin-top: 20px !important;
  }
  .el-dialog__footer {
    height: 66px;
    box-sizing: border-box;
  }
  .editorClass {
    width: 100%;
    height: 100%;
    border: 1px solid #ccc;
  }
  .el-col-12 {
    height: 100%;
  }
}

.video_model {
  width: 48%;
  border-radius: 5px;
  margin-bottom: 20px;

  #video {
    flex: auto;
    height: 85vh !important;
  }

  .video_info {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: 10px;
    line-height: 22px;

    h3 {
      flex: 1;
      padding: 0;
      margin: 0;
      font-weight: 550;
      font-size: 18px;
    }

    .author,
    .blurb {
      font-size: 14px;
    }
  }
}
.analysis {
  width: 48%;
  height: 85vh !important;
  border: 1px solid #ccc;
  overflow: auto;
  .box-card {
    margin-bottom: 10px;
  }
}
</style>
